package com.ssyx.controller;

import com.ssyx.exception.SsyxException;
import com.ssyx.model.acl.Permission;
import com.ssyx.result.Result;
import com.ssyx.result.ResultCodeEnum;
import com.ssyx.service.PermissionService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * @program: ssyx-parent
 * @className: PermissionAdminController
 * @description: 菜单管理
 * @data: 2024/3/7 15:18
 * @author: ihu
 * @version: 1.0
 **/

@Slf4j
@Api(tags = "菜单管理")
@RestController("PermissionAdminController")
@RequestMapping("/admin/acl/permission")
public class PermissionAdminController {
	
	@Resource
	private PermissionService permissionService;
	
	@ApiOperation(value = "获取菜单")
	@GetMapping
	public Result<List<Permission>> index() {
		log.info("获取菜单");
		return Result.ok(permissionService.queryAllMenu());
	}
	
	@ApiOperation(value = "新增菜单")
	@PostMapping("save")
	public Result<?> save(@RequestBody Permission permission) {
		log.info("新增菜单：permission:{}", permission);
		if (permission.getName() == null || permission.getName().isEmpty() || permission.getName().equals(" ")) {
			log.error("新增菜单失败，参数错误");
			throw new SsyxException(ResultCodeEnum.ILLEGAL_PARAM);
		}
		permissionService.save(permission);
		return Result.ok(null);
	}
	
	@ApiOperation(value = "修改菜单")
	@PutMapping("update")
	public Result<?> updateById(@RequestBody Permission permission) {
		log.info("修改菜单：permission:{}", permission);
		permissionService.updateById(permission);
		return Result.ok(null);
	}
	
	@ApiOperation(value = "递归删除菜单")
	@DeleteMapping("remove/{id}")
	public Result<?> remove(@PathVariable Long id) {
		log.info("递归删除菜单：id:{}", id);
		permissionService.removeChildById(id);
		return Result.ok(null);
	}
	
	@ApiOperation(value = "根据用户获取角色数据")
	@GetMapping("/toAssign/{roleId}")
	public Result<List<Permission>> toAssign(@PathVariable Long roleId) {
		log.info("根据用户获取角色数据：roleId:{}", roleId);
		return Result.ok(permissionService.toAssign(roleId));
	}
	
	@ApiOperation(value = "根据用户分配角色")
	@PostMapping("/doAssign")
	public Result<?> doAssign(@RequestParam Long roleId, @RequestParam Long[] permissionId) {
		log.info("根据用户分配角色：roleId:{}，permissionId:{}", roleId, permissionId);
		permissionService.doAssign(roleId, permissionId);
		return Result.ok(null);
	}
}
